package com.matt.service.impl;

import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.rel.RelClassesDoctor;
import com.matt.domain.rel.RelClassesNurse;
import com.matt.foundation.DO.ClassListDO;
import com.matt.foundation.vo.DialogsVo;
import com.matt.repository.ChildrenExtendInfoRepository;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.SystemSettingRepository;
import com.matt.repository.base.ClassesTeacherRepository;
import com.matt.repository.base.ClassesTeachingAreaRepository;
import com.matt.repository.base.UserChildrenRepository;
import com.matt.repository.course.ChildrenCourseItemRepository;
import com.matt.repository.course.CoursePlanRepository;
import com.matt.repository.rel.*;
import com.matt.repository.teaching.TeachingMaterialRepository;
import com.matt.repository.teaching.TeachingPlanRepository;
import com.matt.service.ChildrenService;
import com.matt.service.PhoneUserService;
import com.matt.service.remoteCall.SsoCallService;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Describle This Class Is
 * @Author ZengMin
 * @Date 2018/11/8 17:12
 * @Company Matt
 */
@Service
public class PhoneUserServiceImpl implements PhoneUserService {

    @Autowired
    UserChildrenRepository userChildrenRepository;

    @Autowired
    ChildrenCourseItemRepository childrenCourseItemRepository;

    @Autowired
    CoursePlanRepository coursePlanRepository;

    @Autowired
    ChildrenRepository childrenRepository;

    @Autowired
    ChildrenExtendInfoRepository childrenExtendInfoRepository;

    @Autowired
    RelClassesTeacherRepository relClassesTeacherRepository;

    @Autowired
    RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    ClassesRepository classRepository;

    @Autowired
    SsoCallService ssoCallService;

    @Autowired
    ChildrenService childrenService;

    @Autowired
    TeachingPlanRepository teachingPlanRepository;

    @Autowired
    TeachingMaterialRepository teachingMaterialRepository;

    @Autowired
    SystemSettingRepository systemSettingRepository;

    @Autowired
    RelClassesTeachingAreaRepository relClassesTeachingAreaRepository;

    @Autowired
    ClassesTeachingAreaRepository classesTeachingAreaRepository;

    @Autowired
    private ClassesTeacherRepository classesTeacherRepository;

//
//    private static final String ALL_LIVE_UID = "allLiveUid";
//    private static final String ALL_LIVE_AREA_ID="allLiveAreaId";
//    private static final String ROLE_CODE = "ROLE_GARDEN_LEADER";   //园长code
//    private static final String MBP_LASTMSG_URI = "/api/phone/msg/teach/getLastMsg";
//
//    @Override
//    public List<String> getChildrenByUserId(String userId) {
//        List<String> childrenByUserId = userChildrenRepository.getChildrenIdsByUserId(userId);
//        return childrenByUserId;
//    }
//
//    @Override
//    public Page getCoursePlanByChildren(String childrenId, PagerQuery pagerQuery) {
//        List<ChildrenCourseItem> courseItems = childrenCourseItemRepository.findByChildrenIdOrderByCreatedDesc(childrenId);
//        List<String> coursePlanIds = courseItems.stream().map(o -> o.getCoursePlanId()).collect(Collectors.toList());
//        Pageable pageRequest = PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize());
//        List<CoursePlan> coursePlans = coursePlanRepository.findByIdIn(coursePlanIds, pageRequest);
//        long l = coursePlanRepository.countByIdIn(coursePlanIds);
//        return new PageImpl(coursePlans,pageRequest,l);
//    }
//
//    @Override
//    public List<Children> getChildrenByIds(List<String> ids) {
//        List<Children> all = childrenRepository.findAllById(ids);
//        return all;
//    }
//
//    @Override
//    public List<Map<String, Object>> getCourseExtend(String userId) {
//        List<Map<String, Object>> childrenByIds = userChildrenRepository.getChildrenByUserId(userId);
//        List<Map<String, Object>> list = Lists.newArrayList();
//        for (Map<String, Object> children : childrenByIds) {
//            ChildrenExtendInfo childrenExtendInfo = this.findCourseByCid(children.get("id").toString());
//
//            if(childrenExtendInfo == null){
//                continue;
//            }
//
//            Map<String, Object> map = new HashMap<>();
//            Map<String, Object> nurseryMap = new HashMap<>();
//            Map<String, Object> earlyMap = new HashMap<>();
//            if (childrenExtendInfo.getNurseryStatus() >= 0) {
//                int duration = DateUtil.betweenMonths(childrenExtendInfo.getNurseryEndDate(), new Date());
//                nurseryMap.put("duration", duration < 0 ? "0个月" : duration + "个月");
//                nurseryMap.put("name", "托班");
//                nurseryMap.put("cid", childrenExtendInfo.getChildrenId());
//                nurseryMap.put("status", duration <= 0 ? 1 : 0);
//                nurseryMap.put("endDate", childrenExtendInfo.getNurseryEndDate());
//                nurseryMap.put("startDate",children.get("CourseStartDate"));
//            }else{
//                nurseryMap.put("duration", "0个月");
//                nurseryMap.put("name", "托班");
//                nurseryMap.put("cid", childrenExtendInfo.getChildrenId());
//                nurseryMap.put("status", 0);
//                nurseryMap.put("endDate",null);
//                nurseryMap.put("startDate",null);
//            }
//            if (childrenExtendInfo.getEarlyLeftCourseNum() >= 0) {
//                int duration = childrenExtendInfo.getEarlyLeftCourseNum();
//                earlyMap.put("duration", duration < 0 ? "0节课" : duration + "节课");
//                earlyMap.put("name", "早教");
//                earlyMap.put("cid", childrenExtendInfo.getChildrenId());
//                earlyMap.put("status", duration <= 0 ? 1 : 0);
//                earlyMap.put("startDate",children.get("CourseStartDate"));
//            }else{
//                earlyMap.put("duration","0节课");
//                earlyMap.put("name", "早教");
//                earlyMap.put("cid", childrenExtendInfo.getChildrenId());
//                earlyMap.put("status",  0);
//                earlyMap.put("startDate",null);
//            }
////            String aid = children.get("aid").toString();
////            if(StringUtils.isNotBlank(aid)){
////                AreaDTO area = ssoCallService.getAreaById(aid);
////                map.put("areaMap",area);
////            }
//            map.put("nurseryMap", nurseryMap);
//            map.put("earlyMap", earlyMap);
//            map.put("childrenInfo",children);
//            list.add(map);
//        }
//        return list;
//    }
//
//    @Override
//    public ChildrenExtendInfo findCourseByCid(String cid) {
//        ChildrenExtendInfo childrenExtendInfo = childrenExtendInfoRepository.findByChildrenId(cid);
//        return childrenExtendInfo;
//    }

    /**
     * 1、通过teacherId取班级数
     * 2、通过classId取所有宝宝 通过宝宝id取所有家长
     */
    @Override
    public
    List<Map<String, Object>> getAllParentsByClasses(String areaId,  String staffId, List<ClassListDO> classes){

        List<String> ids = classes.stream().map(k->k.getId()).collect(Collectors.toList());

        List<DialogsVo> dialogsVos = userChildrenRepository.findAllUsersByClassIds(ids);
        { //按classid处理
            Map<String, List<DialogsVo>> cache = new HashMap<>();

            for (DialogsVo object : dialogsVos){
                String classId = object.getClassesId();
                List<DialogsVo> classDialogList = cache.get(classId);
                if(classDialogList == null){
                    classDialogList = new ArrayList<>();
                    cache.put(classId, classDialogList);
                }
                if (StringUtils.isBlank(object.getRelation())) {
                    object.setRelation("家长");
                }
                classDialogList.add(object);
            }

            List<Map<String, Object>> result = Lists.newArrayList();

            for (ClassListDO c : classes) {
                Map<String, Object> map = new HashMap<>();

                map.put("classData", c);
                map.put("linkmanData", cache.get(c.getId()));

                result.add(map);
            }

            return result;
        }
    }

    @Override
    public Map<String, Object> getAllTeachers(String ticket, String areaId,  String staffId, List<ClassListDO> classes) {

        Map<String, Object> result = new HashMap<>();

        for (ClassListDO c : classes){
            result.put(c.getId(), getStaffsByClassId(ticket, areaId, staffId, c));
        }

        return result;
    }

    @Autowired
    private RelClassesNurseRepository relClassesNurseRepository;

    @Autowired
    private RelClassesDoctorRepository relClassesDoctorRepository;

    private Map<String, Object> getStaffsByClassId(String ticket, String areaId, String staffId, ClassListDO classes){

        String classesId = classes.getId();

        //获取所有的
        List<String> teacherIds = relClassesTeacherRepository.findByClassesId(classesId).stream()
                .map(o->o.getStaffId())
                .collect(Collectors.toList());

        //根据classId查询保育员
        List<RelClassesNurse> nurseList = relClassesNurseRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("id").get("linkId").as(String.class), classesId));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        });

        List<String> nurseIds = nurseList.stream().map(o -> o.getId().getDomainId()).collect(Collectors.toList());

        //根据classId查询儿保医生
        List<RelClassesDoctor> doctorList = relClassesDoctorRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("id").get("linkId").as(String.class), classesId));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        });

        List<String> doctorIds = doctorList.stream().map(o -> o.getId().getDomainId()).collect(Collectors.toList());

        //开始拼接
        List<String> ids = new ArrayList<>();
        ids.add(classes.getInChargeTeacherId());
        ids.addAll(teacherIds);
        ids.addAll(nurseIds);
        ids.addAll(doctorIds);

        String[] idsarr = ids.stream().toArray(String[]::new);

        List<StaffDTO> staffs = ssoCallService.getStaffDTOList(ticket, idsarr);
        Map<String, StaffDTO> cache = staffs.stream().collect(Collectors.toMap(StaffDTO::getId, o->o));

        //
        StaffDTO incharge = cache.get(classes.getInChargeTeacherId());
        List<StaffDTO> nurses = nurseIds.stream().map(o->cache.get(o)).filter(o->o!=null).collect(Collectors.toList());
        List<StaffDTO> teachers = teacherIds.stream().map(o->cache.get(o)).filter(o->o!=null).collect(Collectors.toList());
        List<StaffDTO> doctors = doctorIds.stream().map(o->cache.get(o)).filter(o->o!=null).collect(Collectors.toList());

        Map ret = new HashMap();

        ret.put("inChargeTeacher", incharge);
        ret.put("nurses", nurses);
        ret.put("teachers", teachers);
        ret.put("doctors", doctors);

        return ret;
    }

//    @Override
//    public Set<String> getTeachersByChildrenId(String childrenId) {
//        Set<String> result = new HashSet<>();
//        //取班主任 任课老师
//        RelClassesChildren relClassesChildren = relClassesChildrenRepository.findFirstByChildrenId(childrenId);
//        if(relClassesChildren == null){
//            return null;
//        }
//        String classesId = relClassesChildren.getClassesId();
//        List<RelClassesTeacher> byClassesId = relClassesTeacherRepository.findByClassesId(classesId);
//        List<String> teacherIds = byClassesId.stream().map(RelClassesTeacher::getStaffId).collect(Collectors.toList());
//        //取本区域所有园长
//        Children one = childrenRepository.getOne(childrenId);
//        List<String> leads =  ssoCallService.getLeaderByArea(one.getAreaId());
//        result.addAll(teacherIds);
//        result.addAll(leads);
//        return result;
//    }

//    @Override
//    public Set<String> getChildrensByStaffId(String ticket) {
//        Set<String> result = new HashSet<>();
//        StaffRoleDO staffRole = ssoCallService.getStaffRole(ticket);
//        List<Classes> classes = userAccessableClasses(staffRole);
//        List<String> classesId = classes.stream().map(m -> m.getId()).collect(Collectors.toList());
//        List<RelClassesChildren> allByClassesIdIn = relClassesChildrenRepository.findAllByClassesIdIn(classesId);
//        allByClassesIdIn.forEach( o -> {
//            String childrenId = o.getChildrenId();
//            result.add(childrenId);
//        });
//        return result;
//    }

//    @Transactional
//    @Override
//    public boolean updateHeadImg(String cid, String headPath) {
//        Children children = childrenRepository.getOne(cid);
//        children.setImgUrl(headPath);
//        Children children1 = childrenRepository.saveAndFlush(children);
//        return children1 != null;
//    }
//
//    @Override
//    public List<TeachingPlan> getTeachingPlan(String cid, int addDay) {
//        Children children = childrenService.getById(cid);
//        if (Objects.isNull(children)) {
//            throw new BusinessException(CHILDREN_NOT_EXIST, "宝宝不存在！");
//        }
//        Date birthday = children.getBirthday();
//        if (null == birthday) {
//            throw new BusinessException(CHILDREN_BIRTHDAY_NOT_EXIST, "宝宝无生日信息！");
//        }
//        long allDay = DateUtil.betweenDays(birthday, new Date()) + addDay + 2;
//        int month = (int) (allDay / 30) + 1;
//        int day = (int) (allDay % 30) + 1;
//        List<TeachingPlan> list = teachingPlanRepository.findByMonthAndDayAndIsDeletedOrderByFromTime(month, day, false);
//        return list;
//    }
//
//    @Override
//    public TeachingMaterial getTeachingPlanInfo(long id) {
//        TeachingMaterial teachingMaterial = teachingMaterialRepository.getOne(id);
//        return teachingMaterial;
//    }
//
//
//    @Override
//    public List<CoursePlan> getSatCourse(String cid) {
//        List<ChildrenCourseItem> courseItems = childrenCourseItemRepository.findByChildrenIdAndStatus(cid, 1);  //1 表示未上的课
//        List<String> ids = courseItems.stream().map(ChildrenCourseItem::getCoursePlanId).collect(Collectors.toList());
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String date = simpleDateFormat.format(new Date()) + " 00:00:00";
//        List<CoursePlan> coursePlanList = coursePlanRepository.findByIdInAndBeginTimeAfterOrderByCourseDateAsc(ids, DateUtil.parseToDate(date));
//        return coursePlanList;
//    }
//
//    @Override
//    public List<Children> getChildrenBaseInfoByUserId(String uid) {
//        List<Children> children = userChildrenRepository.findByChildrenBaseInfoByUserId(uid);
//        return children;
//    }
//
//    @Override
//    public List<RelClassesChildren> findByChildrenIdIn(List<String> childrenId) {
//        return relClassesChildrenRepository.findByChildrenIdIn(childrenId);
//    }
//
//    @Override
//    public List<RelClassesTeachingArea> findByClassesIdIn(List list) {
//        return relClassesTeachingAreaRepository.findByClassesIdIn(list);
//    }
//
//    @Override
//    public List<LiveRoomDO> findRoomsByChildIdsIn(List list) {
//        return classesTeachingAreaRepository.findRoomsByChildIdsIn(list);
//    }
//
//    private List<Classes> userAccessableClasses( String ticket, StaffDTO staff ){
//
//        if (null == staff) {
//            throw new BusinessException(ErrorCode.TICKET_EXPIRED);
//        }
//
//        ssoCallService.checkStaffPermission()
//
//        String roleCode = staffRole.getRoleCode();
//        List<Classes> classes;
//        if (roleCode.equals(ROLE_CODE)) {
//            //如果是园长  取本区域所有班级
//            String areaId = staff.getAreaId();
//            classes = classRepository.findByAreaId(areaId);
//        } else {
//            String teacherId = staff.getId();
//            classes = classRepository.findByStaffId(teacherId);
//        }
//        return classes;
//    }
}
